var Controller = function()
{
}

Controller.prototype.init = function(canvas, parent)
{
	this.mylatesttap = new Date().getTime();
	this.parent = parent;
	this.objectList = new Array();
	this.mouseX = 0;
	this.mouseY = 0;
	this.mouseLeftState = MouseButtonState.None;
	this.drawableIDCount = 0;
	this.lastElement = null;
	
	this.subsectorbuttons = new Array();
	this.selectedbuttons = new Array();
	this.futurecustomers = new Array();
	
	this.canvas=document.getElementById(canvas);
	
	var that = this;
	
	
	
	
	this.updateTimer = null;
	this.mousePos = {x:0,y:0};
	
	if (this.canvas == null)
	{
		console.log("ERROR: Could not find canvas with ID '" + canvas + "'!");
	}
	else
	{
		this.canvas.addEventListener("mouseout", function(){that.onMouseOut();}, false);
		this.setCanvasContext(this.canvas.getContext('2d'));
		this.setCanvasDimensions(this.canvas.width, this.canvas.height);
		this.canvas.onselectstart = function () { return false; };
		this.buildScene();
		this.update(); // Kick off the loop
		var _this = this;
		this.updateTimer = setInterval(function(){_this.update()}, 1000/60);
		this.initInput();
	}
}

Controller.prototype.onMouseOut = function()
{
	this.clearElementsStateSwitch(ElementState.Hover);
	console.log("Mouse out");
}

Controller.prototype.clearSelected = function()
{
	this.selectedbuttons = new Array();
}

Controller.prototype.addSubSectorButton = function(button)
{
	this.subsectorbuttons.push(button);
}

Controller.prototype.getSubSectorButtonList = function()
{
	return this.subsectorbuttons;
}

Controller.prototype.addSelected = function(button)
{
	this.selectedbuttons.push(button);
}

Controller.prototype.removeSelected = function(button)
{
	this.selectedbuttons.splice(this.selectedbuttons.indexOf(button), 1);
}

Controller.prototype.setLastElement = function(lastelement)
{
	this.lastElement = lastelement;
}

Controller.prototype.getLastElement = function()
{
	return this.lastElement;
}

Controller.prototype.addFutureCustomer = function(button)
{
	this.futurecustomers.push(button);
}

Controller.prototype.removeFutureCustomer = function(button)
{
	this.futurecustomers.splice(this.futurecustomers.indexOf(button), 1);
}

Controller.prototype.disableAllButtons = function()
{
	for(var i=0;i<this.subsectorbuttons.length;i+=1)
	{
		var val = this.subsectorbuttons[i];
		val.disable();
	}
}

Controller.prototype.getElementById = function(id)
{
	for(var i=0;i<this.subsectorbuttons.length;i+=1)
	{
		var val = this.subsectorbuttons[i];
		if (val.getId() == id)
		{
			return val;
		}
	}
	
	return null;
}

Controller.prototype.getMainSectorById = function(id)
{
	switch(id)
	{
		case 1:
			return 'environmental';
		break;
		
		case 2:
			return 'consumers'
		break;
		
		case 3:
			return 'digital'
		break;
		
		case 4:
			return 'industry'
		break;
	}
}

Controller.prototype.getMainElementByName = function(name)
{
	name = name.toLowerCase();
	for(var i=0;i<this.objectList.length;i+=1)
	{
		var val = this.objectList[i];
		var str = val.getName().toLowerCase();
		var newstr = str.replace("|", "");	// Replace newline characters with empty character!
		
		if (newstr == name)
		{
			return val;
		}
	}
	
	return null;
}

Controller.prototype.getElementByName = function(name)
{
	name = name.toLowerCase();
	for(var i=0;i<this.subsectorbuttons.length;i+=1)
	{
		var val = this.subsectorbuttons[i];
		var str = val.getName().toLowerCase();
		var newstr = str.replace("|", "");	// Replace newline characters with empty character!
		
		if (newstr == name)
		{
			return val;
		}
	}
	
	return null;
}

Controller.prototype.enableSection = function(section)
{
	switch(section)
	{
		case "industry":
			this.enableIndustrySection();
		break;
		
		case "consumers":
			this.enableConsumersSection();
		break;
		
		case "digital":
			this.enableDigitalSection();
		break;
		
		case "environmental":
			this.enableEnvironmentalSection();
		break;
	}
}

Controller.prototype.enableIndustrySection = function()
{
	var materialsAndEngineering = this.getElementByName("Materials & Engineering");
	var automotiveAndTransport = this.getElementByName("Automotive & Transport");
	var aerospaceDefenceAndSecurity = this.getElementByName("Aerospace, Defence & Security");
	var industrialChemicalAndMineral = this.getElementByName("Industrial, chemical & mineral");
	var constructionAndBuiltEnvironment = this.getElementByName("Construction & built environment");
	var electronicsAndHardware = this.getElementByName("Electronics & hardware");
	
	materialsAndEngineering.enable();
	automotiveAndTransport.enable();
	aerospaceDefenceAndSecurity.enable();
	industrialChemicalAndMineral.enable();
	constructionAndBuiltEnvironment.enable();
	electronicsAndHardware.enable();
}

Controller.prototype.enableConsumersSection = function()
{
	var publicAdministrationAndEducation = this.getElementByName("Public administration & education");
	var foodAndDrink = this.getElementByName("food & drink");
	var housingClothingAndTextiles = this.getElementByName("Housing, clothing & textiles");
	var leisureAndLifestyle = this.getElementByName("Leisure & lifestyle");
	var landAndProperty = this.getElementByName("Land & property");
	var businessToBusinessServices = this.getElementByName("Business to business services");
	
	publicAdministrationAndEducation.enable();
	foodAndDrink.enable();
	housingClothingAndTextiles.enable();
	leisureAndLifestyle.enable();
	landAndProperty.enable();
	businessToBusinessServices.enable();
	
}

Controller.prototype.enableEnvironmentalSection = function()
{
	var constructionAndBuiltEnvironment = this.getElementByName("Construction & built environment");
	var infrastructureAndUtilities = this.getElementByName("Infrastructure & utilities");
	var environmentalTechnology= this.getElementByName("environmental technology");
	var biotechAndPharma = this.getElementByName("Biotech & Pharma");
	var healthcareAndMedical = this.getElementByName("Healthcare & medical");
	var publicAdministrationAndEducation = this.getElementByName("Public administration & education");
	
	constructionAndBuiltEnvironment.enable();
	infrastructureAndUtilities.enable();
	environmentalTechnology.enable();
	biotechAndPharma.enable();
	healthcareAndMedical.enable();
	publicAdministrationAndEducation.enable();
}

Controller.prototype.enableDigitalSection = function()
{
	var electronicsAndHardware = this.getElementByName("Electronics & hardware");
	var software = this.getElementByName("software");
	var creativeAndMedia = this.getElementByName("creative & media");
	var communications = this.getElementByName("communications");
	var financialServices = this.getElementByName("financial services");
	var businessToBusinessServices = this.getElementByName("Business to business services");
	
	electronicsAndHardware.enable();
	software.enable();
	creativeAndMedia.enable();
	communications.enable();
	financialServices.enable();
	businessToBusinessServices.enable();
}

Controller.prototype.getSelectedList = function()
{
	// Sort the array first
	var idArray = new Array();
	
	for(var i=0;i<this.subsectorbuttons.length;i+=1)
	{
		var but = this.subsectorbuttons[i];
		if (but.getStateSwitch(ElementState.Selected) == true)
		{
			idArray.push(but.getId());
			console.log(but);
		}
	}
	
	/*
	for(var i=0;i<this.selectedbuttons.length;i+=1)
	{
		console.log(this.selectedbuttons[i]);
		idArray.push(this.selectedbuttons[i].getId());
	}
	*/
	return idArray.toString();
}

Controller.prototype.getFutureCustomerList = function()
{
	// Sort the array first
	var idArray = new Array();
	for(var i=0;i<this.subsectorbuttons.length;i+=1)
	{
		var but = this.subsectorbuttons[i];
		if (but.getStateSwitch(ElementState.DblClickSelected) == true)
		{
			idArray.push(but.getId());
			console.log(but);
		}
	}
	/*
	for(var i=0;i<this.futurecustomers.length;i+=1)
	{
		console.log(this.futurecustomers[i]);
		idArray.push(this.futurecustomers[i].getId());
	}
	*/
	return idArray.toString();
}

Controller.prototype.initInput = function()
{
	var c = this.canvas;
	var _this = this;
	c.addEventListener('mousemove', function(event)
	{
		//event.preventDefault();
		_this.mousePos = _this.getMousePos(c, event);
	}
	, false);
	
	c.addEventListener('click', function(event)
	{
		//event.preventDefault();
		console.log("Click");
		_this.setMouseButtonState(MouseButtonState.Down);
		_this.onMousePressed();		
	}
	, false);
	
	c.addEventListener('mouseup', function(event)
	{
		//event.preventDefault();
		_this.onMouseReleased();
		_this.setMouseButtonState(MouseButtonState.None);
	}
	, false);

}

Controller.prototype.getMainSectorId = function(str)
{
	switch(str)
	{
		case 'industry':
			return 4;
		break;
		
		case 'environmental':
			return 1;
		break;
		
		case 'consumers':
			return 2;
		break;
		
		case 'digital':
			return 3;
		break;
	}
}

Controller.prototype.getElementAtPos = function(x, y)
{
	var element = null;
	var maxZ = -1;
	var returnElement = null;
	for(var i=0;i<this.objectList.length;i+=1)
	{
		element = this.objectList[i];
		if (element != null)
		{
			if (element.enabled == true)
			{
				var inBounds = this.testElementBoundary(x, y, element);
				
				if (inBounds == true)
				{
					if (element.getZ() > maxZ)
					{
						returnElement = element;
						maxZ = element.getZ();
					}
				}
			}
		}
	}
	
	return returnElement;
}

Controller.prototype.testElementBoundary = function(x, y, element)
{
	var eBounds = element.getBounds();
	
	switch(element.ShapeGraphicType)
	{
		case Shape.Rectangle:
			return this.boundaryTestRect(x, y, eBounds);
		break;
		
		case Shape.Circle:
			return this.boundaryTestCircle(x, y, eBounds);
		break;
	}
	
	return false;
}

Controller.prototype.boundaryTestRect = function(x, y, bounds)
{
	if (x > bounds.x && y > bounds.y &&
		x < bounds.x + bounds.width && y < bounds.y + bounds.height)
	{
		return true;
	}
	else
	{
		return false;
	}
}

Controller.prototype.boundaryTestCircle = function(x, y, bounds)
{
	if (getDistanceFromTo(x, y, bounds.x, bounds.y) <= bounds.radius)
	{
		return true;
	}
	else
	{
		return false;
	}
}

Controller.prototype.addImage = function(x, y, src)
{
	var image = new ImageGraphic(x, y, src);
	this.addDrawable(image);
	return image;
}

Controller.prototype.onMousePressed = function()
{
	var mPos = this.mousePos;
	var now = new Date().getTime();	
	var timesince = now - this.mylatesttap;
	var element = this.getElementAtPos(mPos.x, mPos.y);
	/*
	if ((timesince < 280) && (timesince > 0))
	{
		if (element == this.getLastElement())
		{
			this.parent.onMouseDblClick(mPos.x, mPos.y, element);
		}
		else
		{
			this.parent.onMouseClick(mPos.x, mPos.y, element);
		}
	}
	else
	{
		this.parent.onMouseClick(mPos.x, mPos.y, element);
	}
	*/
	this.parent.onMouseClick(mPos.x, mPos.y, element);
	

	this.mylatesttap = new Date().getTime();
}

Controller.prototype.clearElementsStateSwitch = function(estate)
{
	var element;
	for(var i=0;i<this.objectList.length;i+=1)
	{
		element = this.objectList[i];
		if (element != null)
		{
			element.setStateSwitch(estate, false);
		}
	}
}

Controller.prototype.onMouseDown = function()
{
	
}

Controller.prototype.onMouseReleased = function()
{

}

Controller.prototype.setMouseButtonState = function(state)
{
	this.mouseLeftState = state;
}

Controller.prototype.getMouseButtonState = function()
{
	return this.mouseLeftState;
}

Controller.prototype.setCanvasContext = function(context)
{
	this.context = context;
}

Controller.prototype.getMousePos = function(canvas, event)
{
	var rect = canvas.getBoundingClientRect();
	return {
          x: (event.clientX - rect.left),
          y: (event.clientY - rect.top)
    };
}

Controller.prototype.buildScene = function()
{
	// Put all code to create the sectors + sub sectors here

	/* This will eventually be the real code 
	this.addSectorIndustry();
	this.addSectorEnvironmental();
	this.addSectorDigital();
	this.addSectorConsumers();
	*/
	this.parent.init();

}

Controller.prototype.addRectangle = function(x, y, w, h, c, hc, sc)
{
	var rect = new ShapeRectangle(x, y, w, h);
	rect.setColor(c);
	rect.setHoverColor(hc);
	rect.setSelectedColor(sc);
	this.addDrawable(rect);
	return rect;
}

Controller.prototype.addLabel = function(x, y, w, h, c, t)
{
	var lbl = new Label(x, y, w, h);
	lbl.setColor(c);
	lbl.setText(t);
	this.addDrawable(lbl);
	return lbl;
}

Controller.prototype.addCircle = function(x, y, r, c, hc, sc)
{
	var circle = new ShapeCircle(x, y, r);
	circle.setColor(c);
	circle.setHoverColor(hc);
	circle.setSelectedColor(sc);
	this.addDrawable(circle);
	return circle;
}

Controller.prototype.addDrawable = function(object)
{
	object.drawId = this.assignDrawId();
	//object.setId("obj_" + object.drawId);
	this.objectList.push(object);
}

Controller.prototype.assignDrawId = function()
{
	this.drawableIDCount+=1;
	return this.drawableIDCount-1;
}

Controller.prototype.drawAll = function()
{
	this.clear();
	this.sortObjectListByZ(this.objectList);
	
	for(var i=0;i<this.objectList.length;i+=1)
	{
		var obj = this.objectList[i];
		if (this.objectList[i].visible)
		{
			obj.draw(this.context);
		}
	}
}

Controller.prototype.setCanvasDimensions = function(w, h)
{
	this.canvasWidth = w;
	this.canvasHeight = h;
}

Controller.prototype.update = function()
{
	this.step();
	this.drawAll();
	//this.setTimer();
}

Controller.prototype.step = function()
{
	// Put all processing to be done each step in this function
	var mPos = this.mousePos;
	this.parent.step(mPos.x, mPos.y);
}

Controller.prototype.setTimer = function()
{
	updateTimer = setTimeout(function(){this.update()}, 1000);
}

Controller.prototype.clear = function()
{
	this.context.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
}

Controller.prototype.sortObjectListByZ = function(drawList)
{
	drawList.sort(this.sortZ);
}

Controller.prototype.sortZ = function(a, b)
{
	if (a.getZ() > b.getZ())
	{
		return 1;
	}
	else if (a.getZ() < b.getZ())
	{
		return -1;
	}
	else if (a.getZ() == b.getZ())
	{
		if (a.getDrawId() > b.getDrawId())
		{
			return 1;
		}
		else
		{
			return -1;
		}
	}
}

